# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 05:55:04 2023

@author: Maxim-Nt
"""

import pickle
from LodgerItem import LodgerItem

class PickleStorage:
    def __init__(self, lodger):
        self.lodger = lodger
        try:
            self.Load()
        except:
            self.items = {}
            self.maxid = 0
    """
    def store(self):
        pickle.dump((self.lodger.maxID, self.lodger.items), 
                    open("data.dat", "wb"))
        
    def load(self):
        (self.lodger.maxID, self.lodger.items) = pickle.load(
            open("data.dat", "rb"))
        """
    def Load(self):
        with open('lodger.db', 'rb') as f:
            (self.maxid, self.items) = pickle.load(f)
        
    def Store(self):
        with open('lodger.db', 'wb') as f:
            pickle.dump((self.maxid, self.items), f)

    def GetItem(self, id):
        if id <= 0:
            return LodgerItem()
        else:
            return self.items[id]

    def Add(self, item):
        if item.id <= 0:
            self.maxid += 1;
            item.id = self.maxid
            self.items[item.id] = item
            
    def Delete(self, id):
        del self.items[id]
        
    def GetItems(self):
        for(id, item) in self.items.items():
            yield(item)
